package cn.comtom.ewbs.signature.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;

import cn.comtom.ewbs.signature.common.enums.SysConstant;
import cn.comtom.ewbs.signature.common.vo.request.BatchIdsReq;
import cn.comtom.ewbs.signature.common.vo.request.PageRequest;
import cn.comtom.ewbs.signature.common.vo.response.ApiPageResponse;
import cn.comtom.ewbs.signature.common.vo.response.ApiResponse;
import cn.comtom.ewbs.signature.entity.SignApply;
import cn.comtom.ewbs.signature.service.ISignApplyService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuhy
 * @since 2022-11-08 18:12:05
 */
@Controller
@RequestMapping("/auth/SignApplyController")
@Slf4j
@Validated
@Api(tags = "证书申请管理", description = "证书申请管理")
public class SignApplyController extends AuthController {

	private String prefix = "admin/signApply";
	
	@Autowired
	private ISignApplyService signApplyService;
	
	/**
	 * 页面展示
	 * @param model
	 * @return String
	 * @author fuce
	 */
	@ApiOperation(value = "分页跳转", notes = "分页跳转")
	@GetMapping("/view")
	//@SaCheckPermission("gen:signDev:view")
    public String view(ModelMap model){
        return prefix + "/list";
    }
	
	/**   
     * 分页查询
     * @param signApply 请求参数 
     * @param pageReq   分页参数
     * @return ApiPageResponse 响应结果     
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @ResponseBody
    public ApiPageResponse<SignApply> page(@ModelAttribute SignApply signApply, @ModelAttribute PageRequest pageReq) {
    	IPage<SignApply> pager = signApplyService.selectPage(signApply,pageReq);
        return ApiPageResponse.ok(pager);
    }
	

    /**
     * 根据ID删除
     * @param id 主键
     * @return 响应结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    @ResponseBody
    public ApiResponse deleteById(@PathVariable(name = "id") String id){
    	if(signApplyService.removeById(id)) {
    		return ApiResponse.ok();
    	}else {
    		return ApiResponse.error();
    	}
    }
    
    /**
     * 根据ID批量删除
     * @param id 主键
     * @return 响应结果
     */
    @DeleteMapping("/batchDeleteByIds")
    @ApiOperation(value = "根据ID批量删除", notes = "根据ID批量删除")
    @ResponseBody
    public ApiResponse batchDeleteByIds(@RequestBody BatchIdsReq req){
    	signApplyService.removeBatchByIds(req.getIds());
    	return ApiResponse.ok();
    }
    
	/**
     * 新增跳转
     */
	@ApiOperation(value = "新增跳转", notes = "新增跳转")
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        return prefix + "/add";
    }
	
    @PostMapping("/uploadApplyFile")
    @ApiOperation(value = "上传信任关系文件", notes = "上传信任关系文件")
    @ResponseBody
    public ApiResponse uploadApplyFile(@RequestPart("txtFile")  MultipartFile txtFile) {
    	try {
    		FileUtil.mkdir(SysConstant.SYS_TMP_DIR);
    		String tmpFilePath = SysConstant.SYS_TMP_DIR.concat(IdUtil.fastSimpleUUID()).concat(".txt");
    		IoUtil.copy(txtFile.getInputStream(), new FileOutputStream(tmpFilePath));
			File tFile =  FileUtil.newFile(tmpFilePath);
			List<String> lines = FileUtil.readUtf8Lines(tFile);
    		
			lines = lines.stream().filter(StrUtil::isNotBlank).collect(Collectors.toList());
    		SignApply signApply = new SignApply();
    		signApply.setApplyFileName(txtFile.getOriginalFilename());
    		signApply.setApplyStatus(0);
    		signApply.setApplyDevNum(lines.size());
    		signApply.setCreator(getCurrentUserInfo().getAccount());
    		signApply.setCreateTime(LocalDateTime.now());
    		signApply.setApplyResult("未申请");
			signApply.setApplyFile(FileUtil.readBytes(tFile));
			signApplyService.saveOrUpdate(signApply);
			FileUtil.del(tmpFilePath);
		} catch (IOException e) {
			e.printStackTrace();
			return ApiResponse.error();
		}
    	return ApiResponse.ok();
    }

    
    /**
     * 证书和信任链申请
     * @param signApply 请求数据
     * @return 响应结果
     * @throws IOException 
     */
    @PostMapping("/applyCert")
    @ApiOperation(value = "证书和信任链申请", notes = "证书和信任链申请")
    @ResponseBody
    public ApiResponse signApply(@RequestParam(name="id") String id) throws IOException{
    	if(signApplyService.signApply(id,getCurrentUserInfo().getAccount())) {
    		return ApiResponse.ok();
    	}else {
    		return ApiResponse.error();
    	}
    }
    
	/**
	 * 下载
	 * 
	 */
	@GetMapping("/down")
	@ResponseBody
	public ApiResponse down(@RequestParam(name="id")String id) throws IOException {
		SignApply sa = signApplyService.getById(id);
		if(sa != null && sa.getResultFile()!=null) {
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\""+sa.getResultFileName()+"\"");
			response.addHeader("Content-Length", "" + sa.getResultFile().length);
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.getOutputStream().write(sa.getResultFile());
		}
		return ApiResponse.error();
	}

}
